// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::Manager; //, WindowBuilder, WindowUrl
use std::process::Command;
// use std::thread;
// use std::time::Duration;
use std::env;


// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn get_desktops() -> String {
    exec_des_lib()
}

fn exec_des_lib()->String{
    let output = Command::new("start.exe")
    .arg("fromRust")
    .output()
    .expect("Failed to execute process");
    let r= String::from_utf8_lossy(&output.stdout).to_string();
    //println!("Program output: {}",r);
    r      
} 

use tauri::{CustomMenuItem, Menu, MenuItem, Submenu};
/* 
const INIT_SCRIPT: &str = r#"
  //if (window.location.origin === 'https://tauri.app') {
  console.log(window.location.href  );
  //if (window.location.origin === 'index1.html') {
    console.log("hello world from js init script");
    console.log("hello world from js init script");

    window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
    alert('from init script!!!');
  //}
"#;
*/
const INIT_SCRIPT: &str  = include_str!("init.js");

fn main() {
    // 判断参数来源

    

    // 获取命令行参数
    let args: Vec<String> = env::args().collect();
 
    // 打印程序名
    println!("Program name: {}", args[0]);
 
    // 打印其他参数
    for arg in args.iter().skip(1) {
        println!("{}", arg);
    }

    // 创建新线程
    // thread::spawn(|| {
    //     loop {
    //         // 在新线程中运行外部程序
    //         let output = exec_des_lib();

    //         // 打印输出结果
    //         println!(
    //             "Program output: {}",
    //             output
    //         );
    //         thread::sleep(Duration::from_secs(1))
    //     }
    // });

    // 这里 `"quit".to_string()` 定义菜单项 ID，第二个参数是菜单项标签。
let quit = CustomMenuItem::new("quit".to_string(), "退出");
let close = CustomMenuItem::new("close".to_string(), "关闭");
let submenu = Submenu::new("File", Menu::new().add_item(quit).add_item(close));
let menu = Menu::new()
  .add_native_item(MenuItem::Copy)
  .add_item(CustomMenuItem::new("hide", "Hide"))
  .add_submenu(submenu);
/*
     "windows": [{
        
        "title": "主窗口",
        "width": 800,
        "height": 600,
        "url": "http://localhost:8081/index1.html" 
        
      }
    ]

   
    tauri::Builder::default()
        .setup(|app| {
            let window = app.get_window("main").unwrap();
            // window.set_always_on_top(true)?;
            // window.set_fullscreen(true)?;
            // print!("{}", window.url());
            window.open_devtools();
            // window.close_devtools();

            // window.eval("window.location.replace('https://www.baidu.com/')")?;
            
            Ok(())
        })
        
        .menu(menu)
        .on_menu_event(|event| {
            match event.menu_item_id() {
              "quit" => {
                std::process::exit(0);
              }
              "close" => {
                event.window().close().unwrap();
              }
              _ => {}
            }
          })
        .invoke_handler(tauri::generate_handler![greet,get_desktops])
        
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
    */

        tauri::Builder::default()
        .setup(|app| {
            // let window = tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index1.html".into()))
            let window = tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::External("http://172.16.10.111:5886".parse().unwrap()))
            .title("八维考试系统")
            .initialization_script(INIT_SCRIPT)
            .build()?;
             window.open_devtools();
          Ok(())
        })
        
        .invoke_handler(tauri::generate_handler![greet,get_desktops])
        
        .run(tauri::generate_context!())
        .expect("error while running tauri application");


    // let app = tauri::Builder::default()
    // .setup(|app| {
    //     let main_window = app.get_window("main").unwrap();
    //     print!( "{}",main_window.url());
    //     main_window.eval("window.location.replace('https://tauri.app/')")?;
    //     Ok(())
    //   })
    //     .invoke_handler(tauri::generate_handler![greet])
    //     .build(tauri::generate_context!())
    //     .expect("error while building tauri application");

    // tauri::WindowBuilder::new(
    //     &app,
    //     "external", /* the unique window label */
    //     tauri::WindowUrl::External("https://tauri.app/".parse().unwrap()),
    // )
    // .build()
    // .expect("failed to build window");

    // tauri::Builder::default()
    // .setup(|app| {
    //   WindowBuilder::new(
    //     app,
    //     "external",
    //     WindowUrl::External("http://yjmyzz.cnblogs.com/".parse().unwrap()),
    //   )
    //   .title("菩提村下的杨过")
    //   .inner_size(640.0, 480.0)
    //   .position(50.0, 100.0)
    //   .build()?;
    //   Ok(())
    // })
    // .run(tauri::generate_context!())
    // .expect("error while running tauri application");
}
